"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 功能测试
Case Name   : 结合timecapsule timestamp,timecapsule csn指定日期及csn闪回查询
Create At   : 2022/11/21
Owner       : opentestcase034
Description :
            1、设置undo旧版本保留时间为3600
            2、创建表
            3、在表中插入数据
            4、查询创建的表
            5、删除表数据
            6、闪回查询表数据并将结果插入到表
            7、查询插入的表
            8、清理环境
Expect      :
            1、成功
            2、成功
            3、成功
            4、成功
            5、成功
            6、成功
            7、成功
            8、成功
History     :
"""

import os
import re
import time
import unittest
from yat.test import Node
from yat.test import macro

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class SQL(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.Constant = Constant()
        self.pri_node = Node('PrimaryDbUser')
        self.env_path = macro.DB_ENV_PATH
        self.t_name1 = 't_select_into_0042_1'
        self.t_name2 = 't_select_into_0042_2'
        self.t_name3 = 't_select_into_0042_3'
        self.config_undo = 'undo_retention_time'

    def test_timecapsule_table(self):
        step1 = '--step1:设置undo旧版本保留时间为3600;expect:成功--'
        self.log.info(step1)
        msg = self.primary_sh.execute_gsguc('reload',
                                            self.Constant.GSGUC_SUCCESS_MSG,
                                            f'{self.config_undo} = 3600')
        self.assertTrue(msg, '执行失败' + step1)

        step2 = '--step2:创建表;expect:成功--'
        self.log.info(step2)
        sql_cmd = f'drop table if exists {self.t_name1};' \
                  f'create table {self.t_name1} (' \
                  f'idx integer, ' \
                  f'snaptime timestamp, ' \
                  f'snapcsn bigint, ' \
                  f'timeDesc character(100)) ' \
                  f'with (storage_type=ustore);'
        result = self.primary_sh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.Constant.TABLE_DROP_SUCCESS, result,
                      '执行失败' + step2)
        self.assertIn(self.Constant.CREATE_TABLE_SUCCESS, result,
                      "执行失败" + step2)

        step3 = '--step3:在表中插入数据;expect:成功--'
        self.log.info(step3)
        sql_cmd = f"insert into {self.t_name1} " \
                  f"select 1, now(),int8in(xidout(next_csn)), 'time1' " \
                  f"from gs_get_next_xid_csn();"
        result = self.primary_sh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.Constant.INSERT_SUCCESS_MSG, result,
                      '执行失败' + step3)
        time.sleep(5)
        sql_cmd = f"insert into {self.t_name1} " \
                  f"select 2, now(),int8in(xidout(next_csn)), 'time2' " \
                  f"from gs_get_next_xid_csn();"
        result = self.primary_sh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.Constant.INSERT_SUCCESS_MSG, result,
                      '执行失败' + step3)
        time.sleep(5)
        sql_cmd = f"insert into {self.t_name1} " \
                  f"select 3, now(),int8in(xidout(next_csn)), 'time3' " \
                  f"from gs_get_next_xid_csn();"
        result = self.primary_sh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.Constant.INSERT_SUCCESS_MSG, result,
                      '执行失败' + step3)
        time.sleep(5)
        sql_cmd = f"insert into {self.t_name1} " \
                  f"select 4, now(),int8in(xidout(next_csn)), 'time4' " \
                  f"from gs_get_next_xid_csn();"
        result = self.primary_sh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.Constant.INSERT_SUCCESS_MSG, result,
                      '执行失败' + step3)

        step4 = '--step4:查询创建的表;expect:成功--'
        self.log.info(step4)
        sql_cmd = f'select snaptime from {self.t_name1} where idx = 4;'
        result = self.primary_sh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertRegex(result, '\d+-\d+-\d+ \d+:\d+:\d+\.\d+',
                         '执行失败' + step4)
        t_time = re.findall('\d+-\d+-\d+ \d+:\d+:\d+\.\d+',
                            result)[0]
        sql_cmd = f'select snapcsn from {self.t_name1} where idx = 4;'
        result = self.primary_sh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertRegex(result, '\d+', '执行失败' + step4)
        t_csn = re.findall('\d+', result)[0]

        step5 = '--step5:删除表数据;expect:成功--'
        self.log.info(step5)
        sql_cmd = f'delete from {self.t_name1};'
        result = self.primary_sh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.Constant.DELETE_SUCCESS_MSG, result,
                      '执行失败' + step5)

        step6 = '--step6:闪回查询表数据并将结果插入到表;expect:成功--'
        self.log.info(step6)
        sql_cmd = f"select * into {self.t_name2} " \
                  f"from {self.t_name1} " \
                  f"timecapsule timestamp " \
                  f"to_timestamp('{t_time}','YYYY-MM-DD HH24:MI:SS.FF');" \
                  f"select * into {self.t_name3} " \
                  f"from {self.t_name1} " \
                  f"timecapsule csn {t_csn};"
        result = self.primary_sh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertEqual(2, result.count(self.Constant.INSERT_SUCCESS_MSG),
                         '执行失败' + step6)

        step7 = '--step7:查询插入的表;expect:成功--'
        self.log.info(step7)
        sql_cmd = f'''
                    select * from {self.t_name2};
                    select * from {self.t_name3};
                    '''
        result = self.primary_sh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertEqual(2, result.count('time1'), '执行失败' + step7)
        self.assertEqual(2, result.count('time2'), '执行失败' + step7)
        self.assertEqual(2, result.count('time3'), '执行失败' + step7)

    def tearDown(self):
        step8 = '--step8:清理环境;expect:成功--'
        self.log.info(step8)
        sql_cmd = f'''
                    drop table if exists {self.t_name1};
                    drop table if exists {self.t_name2};
                    drop table if exists {self.t_name3};
                    '''
        result = self.primary_sh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertEqual(3, result.count(self.Constant.DROP_TABLE_SUCCESS),
                         '执行失败' + step8)
        msg = self.primary_sh.execute_gsguc('reload',
                                            self.Constant.GSGUC_SUCCESS_MSG,
                                            f'{self.config_undo} = 0')
        self.assertTrue(msg, '执行失败' + step8)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')